import datetime
import os.path

import pandas as pd
import sys

sys.path.append("..")
from tools.utils import load_config
from tools.utils import get_chinese_name_to_ts_code
from tools.utils import download_wind_edb
from tools.utils import loc_collection, loc_zq_collection


def upload_spot_stock_config(cfg, kind="现货", mode='ini'):
    """
    :param cfg:dict from yaml
    :param kind:str > 现货 or 库存
    :param mode:str > ini or update
    :return:
    """
    collection_map = {'现货': 'future_spot_price', '库存': 'future_stock_data'}
    cnttc = get_chinese_name_to_ts_code(cfg)
    collection_ = loc_collection('project_config', collection_map[kind])
    cache_li = []
    all_database_li = list(collection_.find())
    all_data_dic = {s['指标ID']: s for s in all_database_li}
    for category, chinese_names in cfg['tjd_category'].items():
        for chinese_name in chinese_names:
            ts_code = cnttc[chinese_name]
            symbol = ts_code.split('_')[0].upper()
            pth = f"../data/future_meta_data/{chinese_name}_{kind}.xlsx"
            if os.path.exists(pth):
                data = pd.read_excel(pth, index_col=0)
                data = data.iloc[:8, :]
                cache_li.append((pth, data, symbol, ts_code, chinese_name))
    for seconde_li in cache_li:
        pth, data, symbol, ts_code, chinese_name = seconde_li
        for k, v in data.iteritems():
            v_dic = v.to_dict()
            v_dic["ts_code"] = ts_code
            v_dic["symbol"] = symbol
            v_dic['chinese_name'] = chinese_name
            v_dic['freq'] = v_dic['频率']
            today = str(datetime.date.today())[:10]
            if mode == 'ini':
                v_dic['update_date'] = today
                v_dic = download_wind_edb(v_dic)
                if len(v_dic['v']) > 100:
                    collection_.insert(v_dic)
                else:
                    print('fail >>', v_dic)
            else:
                id_ = v_dic['指标ID']
                database_dic = all_data_dic[id_]
                if database_dic['t'][-1] < today:
                    collection_.delete_many({'指标ID': id_})
                    v_dic['update_date'] = database_dic['update_date']
                    v_dic = download_wind_edb(v_dic)
                    if len(v_dic['v']) > 100:
                        collection_.insert_one(v_dic)
                        print(f"database{database_dic['指标名称']}to{v_dic['t'][-1]}。")
                    else:
                        print('fail >>', v_dic)
                else:
                    print(f"database{database_dic['指标名称']}已经是最新不需要更新。")
    print("Done!!!")
    return list(collection_.find())


def upload_spot_stock_from_zhouqi(mode='现货'):
    today = str(datetime.date.today())
    collection_map = {'现货': 'future_spot_price', '库存': 'future_stock_data'}
    coll_ = loc_collection('project_config', collection_map[mode])
    coll_zq = loc_zq_collection('wind_edb', 'data')
    data_li = list(coll_.find())
    for dic in data_li:
        zq_li = list(coll_zq.find({'__id':dic['指标ID']}))
        if len(zq_li) > 0:
            dic_zq = zq_li[0]
            latest = str(dic_zq['index'][-1])
            print('zq', latest, 'old', dic['update_date'], dic['指标名称'])
            dic['update_date'] = today
            dic['t'] = [str(s)[:10] for s in dic_zq['index']]
            dic['v'] = dic_zq['data']
            coll_.save(dic)


if __name__ == "__main__":
    upload_spot_stock_from_zhouqi('库存')